<template lang="">
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="user-list">
            <!-- 搜索与用户添加 -->
            <el-row :gutter=20>
                <el-col :span=7>
                    <el-input placeholder="请输入内容" v-model='queryInfo.query' clearable @clear="clearSearch">
                        <el-button slot="append" icon="el-icon-search" @click='getUserList'></el-button>
                    </el-input>
                </el-col>
                <el-col :span=5>
                    <el-button type="primary" @click="addUserDialog = true">用户添加</el-button>
                    <el-dialog title="用户添加" width="50%"  :visible.sync="addUserDialog" @close='resetAddUser'>
                      <el-form :model="addUser" ref="addUserRef" label-width="80px" :rules="addUserRules">
                        <el-form-item label="用户名" prop="username">
                          <el-input v-model="addUser.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                          <el-input v-model="addUser.password" ></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱"  prop="email">
                          <el-input v-model="addUser.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机" prop="mobile">
                          <el-input v-model="addUser.mobile"></el-input>
                        </el-form-item>
                      </el-form>
                      <span slot="footer" class="dialog-footer">
                        <el-button @click="addUserDialog = false">取 消</el-button>
                        <el-button type="primary" @click="submitUserForm">确 定</el-button>
                      </span>
                    </el-dialog>
                </el-col>
            </el-row>
            <el-table :data="userList" border style="width: 100%" :stripe='true'>
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch
                        v-model="scope.row.mg_state"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        @change='changeStatus(scope.row)'>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="handle" label="操作">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable='false'>
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click='changeUser(scope.row)'></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable='false'>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click='deleteUser(scope.row)'></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="权限分配" placement="top" :enterable='false'>
                            <el-button type="warning" icon="el-icon-setting" size="mini" ></el-button>
                        </el-tooltip>
                        <el-dialog
                          title="修改用户信息"
                          :visible.sync="editorDialog"
                          width="50%">
                          <el-form ref="userChangeRef" :model="userChange" label-width="80px" :rules="addUserRules">
                            <el-form-item label="用户名">
                              <el-input v-model="userChange.username" :disabled="true"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                              <el-input v-model="userChange.email"></el-input>
                            </el-form-item>
                            <el-form-item label="手机" prop="mobile">
                              <el-input v-model="userChange.mobile"></el-input>
                            </el-form-item>
                          </el-form>
                          <span slot="footer" class="dialog-footer">
                            <el-button @click="editorDialog = false">取 消</el-button>
                            <el-button type="primary" @click="changeUserEnter(scope.row)">确 定</el-button>
                          </span>
                        </el-dialog>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
    </div>
</template>
<script>
export default {
  data () {
    var mobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 10,
      searchList: '',
      addUserDialog: false,
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userChange: {
        username: '',
        email: '',
        mobile: ''
      },
      editorDialog: false,
      addUserRules: {
        username: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: mobile, message: '请输入正确的手机', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message({
          message: 'error',
          type: 'error'
        })
      } else {
        this.userList = res.data.users
        this.total = res.data.total
      }
    },
    changeStatus (userInfo) {
      this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      this.$message({
        message: '用户状态修改成功',
        type: 'success'
      })
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getUserList()
    },
    clearSearch () {
      this.getUserList()
    },
    submitUserForm () {
      this.$refs.addUserRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addUser)
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message({
              message: '获取用户信息失败',
              type: 'error'
            })
          } else {
            this.addUserDialog = false
            this.getUserList()
            this.$message({
              message: '用户添加成功',
              type: 'success'
            })
          }
        } else {
          console.log('用户添加失败')
          return false
        }
      })
    },
    async changeUser (userInfo) {
      const { data: res } = await this.$http.get(`users/${userInfo.id}`)
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取用户信息失败',
          type: 'error'
        })
      } else {
        this.userChange = res.data
      }
      this.editorDialog = true
    },
    changeUserEnter (userInfo) {
      this.$refs.userChangeRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(`users/${userInfo.id}`, { email: this.userChange.email, mobile: this.userChange.mobile })
          if (res.meta.status !== 200) {
            this.message.error('更新用户信息失败')
          } else {
            this.getUserList()
            this.$message({
              message: '更新用户信息成功',
              type: 'success'
            })
          }
        } else {
          return false
        }
      })
      this.editorDialog = false
    },
    resetAddUser () {
      this.$refs.addUserRef.resetFields()
    },
    deleteUser (userInfo) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + userInfo.id)
        if (res.meta.status !== 200) {
          return this.message.error('删除用户失败')
        } else {
          this.getUserList()
          return this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
    font-size: 12px;
}
.el-card {
    background: #fff;
    margin-top: 20px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 5%) !important;
    .user-search{
        .el-input{
            width: 300px;
            margin-bottom: 20px;
        }
    }
    .el-table{
      margin: 20px 0;
    }
}
</style>
